package com.stock.util;

import com.stock.entity.UserEntity;
import com.stock.service.IPointUsageRecordService;
import com.stock.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Component
public class PointValidatorUtil {

    private final IUserService userService;

    private final IPointUsageRecordService pointUsageRecordService;

    public PointValidatorUtil(IUserService userService, IPointUsageRecordService pointUsageRecordService) {
        this.userService = userService;
        this.pointUsageRecordService = pointUsageRecordService;
    }

    /**
     * 校验积分并扣除 10
     * @param username 用户名
     * @throws RuntimeException 如果积分不足
     */
    public void checkAndDeductPoint(String username) {
        UserEntity user = userService.getUserInfoByUserName(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
//        // 判断当天是否使用积分查询过
//        if (pointUsageRecordService.hasUsedToday(username)) {
//            return; // 当天已使用积分，不扣除
//        }
        // 校验积分
        Integer point = user.getPoint();
        if (point <= 0) {
            throw new RuntimeException("积分不足");
        }
        // 扣除积分
        user.setPoint(point - 1);
        userService.updateById(user);
        // 添加积分使用记录
        pointUsageRecordService.addUsageRecord(username);
    }

    /**
     * 校验当前用户的积分并扣除 10
     * @throws RuntimeException 如果积分不足
     */
    public void checkAndDeductCurrentUserPoint() {
        // 获取当前认证的用户名
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        this.checkAndDeductPoint(username);
    }
}
